<template>
  <div class="menu-link-lib">
  <!--按钮组-->
  <div class="Btns-ctrl-body btns-under-box">

    <div class="search-ctrl f-l ">
      <input type="text" class="search-text" placeholder="搜索菜单名称" v-model="searchStr">
      <button type="button" class="search-btn btn btn-info" @click="btnSearch(pageSize, 0)">搜索</button>
    </div>


    <div class="btns f-r">
      <button type="button"
        class="btn btn-info"
        @click="btnAdd" >
        新增
      </button>
      <button type="button"
        class="btn btn-warning"
        @click="btnRevise" >
        修改
      </button>
      <button type="button"
        class="btn btn-danger"
        @click="btnDelete" >
        删除
      </button>
    </div>
  </div>
  <!--按钮组闭合-->
  <!-- tree-table-gride -->
 <div class="contains">
    <h1>树表格实现</h1>
    <tree-table ref="recTree" :list.sync="treeDataSource" @actionFunc="actionFunc" @deleteFunc="deleteFunc" @handlerExpand="handlerExpand" @orderByFunc="orderByFunc"></tree-table>
  </div>
  <!-- tree table关闭 -->
    <!-- 弹框 -->
    <vdialog :DialogToggle = DialogToggle
        :dialogObject = dialogObject></vdialog>
  </div>
</template>

<script>
import vdialog from 'sudoku/atom/vdialog'
import { searchMenu } from '@/api/menu'
import treeTable from 'sudoku/atom/tree-table/tree-table'
import dataJson from './data.json'
import SearchPublic from "../../publicTemplate/search/SearchPublic"

export default {
  name: 'menuLinkLib_1',
  data() {
    return {
      props: {
        stripe: true,        //是否显示间隔斑马纹
        border: true,        //是否显示纵向边框
        showHeader: true,    //是否显示表头
        showSummary: false,  //是否显示表尾合计行
        showRowHover: true,  //鼠标悬停时，是否高亮当前行
        showIndex: true,     //是否显示数据索引
        treeType: true,      //是否为树形表格
        isFold: true,        //树形表格中父级是否默认折叠
        expandType: false,   //是否为展开行类型表格
        selectionType: false  //是否为多选类型表格
      },
      columns: [            //列表头部信息
        {
          label: 'name',
          prop: 'name',
          width: '200px',
        },
        {
          label: 'displayName',
          prop: 'displayName',
          minWidth: '250px',
          type: 'template',
          template: 'displayName',
        },
        {
          label: 'target',
          prop: 'target',
        },
        {
          label: 'remark',
          prop: 'remark',
          minWidth: '200px',
        },
      ],
      dataMenuList: [],         //表格初始化数据

      PicErr: 'this.src="' + require('@/assets/error.png') + '"',  //img加载失败的图片

      pageSize: 10,             //分页每页显示条数
      searchStr: '',           //搜索的输入框字段
      DialogToggle: false,       //弹窗显示控制字段
      dialogObject: {
        "title": '新建菜单'
      },

      checkedAry: [],              //表单选中的index数组

      checkedItem: [],           //点击选中的值存放处

      rowList: [],               //存放点中的事件

      list: dataJson,
      treeDataSource: dataJson,
      searchObj:{
        condition:[
          {"title":"名称","key":"name",'type':'text',"value":'','data':''},
        ],
        htmlType:"searchDefaultPublic",
      },
    }
  },
  computed: {

  },
  methods: {
    /**
     * 返回文件服务的地址
     */
    PicSrc(scope) {
      if(scope != null && scope.row != null
        && scope.row.imgModel != null
        && scope.row.imgModel.storeId != null){
        let storeId = scope.row.imgModel.storeId
        return baseURL                                          //运行环境
          + 'api/jp-TIFS-FileCenter-ms/file?businessId='  //微服务地址
          + storeId
      }
    },
    btnSearch(pageSize, current) {
      let data = {
        'name': this.searchStr,
        'curPage': current,
        'pageSize': pageSize
      };
      searchMenu(data).then( res => {
        let data = res.data;
        let count = res.data.count;           //总数据量
        this.dataMenuList = data.menuList;
      })
    },
    btnAdd() {
      this.DialogToggle = !this.DialogToggle;
      this.dialogTitle = '新建菜单';
    },
    btnRevise() {
    },
    btnDelete() {},
    rowClick(row, rowIndex, event) {
      //2为通过template上img的自定义属性data-id获取id然后对数据进行操作
      let id = row.currentTarget.childNodes[2].getElementsByTagName('img')[0].getAttribute('data-id');
      //先判断this.checkedItem中是否有点击的id如果有就删除并且移走class，没有就添加
      let ischecked = this.toggleJSON(this.checkedItem, 'id', id);
      if(ischecked) {//true取消选择，undefined选择
        this.checkedRemoveClass(row)
      }
      else {
        //点击数据保存到数组的方法 this.checkedItem用来存放点击项的数据
        this.aryFindChildre(this.dataMenuList, 'id', id)
        this.checkedAddClass(row)
      }

      // if(this.checkedItem[0]) {//数组不为空的时候去重
      //   this.checkedItem = this.uniqueArray(this.checkedItem, 'id')
      // }

      //console.log(this.checkedItem)
    },
    toggleJSON(ary, attr, value) {
      for(let i = 0; i < ary.length; i++){
        if(ary[i][attr] == value) {//相等就删除，代表取消选择
          ary.splice(i, 1)
          return true;
        }
      }
    },

    //选中增加选中样式
    checkedAddClass(row) {
      row.currentTarget.style.color = '#fff';
      row.currentTarget.style.background = '#009aff' ;
      row.currentTarget.children[0].children[0].style.background = 'url('+ require('@/assets/true.png')+') no-repeat' ;
    },
    //取消选中样式
    checkedRemoveClass(row) {
      row.currentTarget.style.color = '#000';
      row.currentTarget.style.background = '#fff' ;
      row.currentTarget.children[0].children[0].style.background = '' ;
    },
    /**
     * ary 需要遍历的数组， attr需要对比的值 id对比的值
     * this.checkedItem 全局变量存放数据
     */
    aryFindChildre( ary, attr , id) {
      const self = this;
      if(ary != null) {
        for(let i = 0; i < ary.length; i++){
          if(ary[i][attr] === id) {
            self.checkedItem.push(ary[i]);
            break;
          }
          else if(ary[i].children != null ){
            self.aryFindChildre(ary[i].children, attr, id)
          }
        }
      }
    },
    /* * JSON数组去重
    * @param: [array] json Array
    * @param: [string] 唯一的key名，根据此键名进行去重
    */
    uniqueArray(array, key){
      var result = [array[0]];
      for(var i = 1; i < array.length; i++){
        var item = array[i];
        var repeat = false;
        for (var j = 0; j < result.length; j++) {
          if (item[key] == result[j][key]) {
            repeat = true; break;
          }
        } if (!repeat) {
            result.push(item);
          }
      }
      return result;
    },

    orderByFunc(val) {
      alert('排序')
      alert(val)
    },
    actionFunc(m) {
      alert('编辑')
    },
    deleteFunc(m) {
      alert('删除')
    },
    handlerExpand(m) {
      //console.log('展开/收缩')
      m.isExpand = !m.isExpand
    },
    getTreeData() {
      // 取父节点
      let parentArr = this.list.filter(l => l.parentId === 0)
      this.treeDataSource = this.getTreeData(this.list, parentArr)
    },
    // 这里处理没有children结构的数据
    getTreeData(list, dataArr) {
      dataArr.map((pNode, i) => {
        let childObj = []
        list.map((cNode, j) => {
          if (pNode.Id === cNode.parentId) {
            childObj.push(cNode)
          }
        })
        pNode.children = childObj
        if (childObj.length > 0) {
          this.getTreeData(list, childObj)
        }
      })
      return dataArr
    }
  },
  components: {
    vdialog,
    treeTable,
    SearchPublic
  },
  created() {
    this.btnSearch(this.pageSize, 0)
  },
  watch: {

  }
}
</script>

<style lang="scss" scoped>
  .menu-link-lib {
    overflow: auto;
    .btn-slot-dialog {
      width: 80px;
      height: 32px;
      padding: 0 10px;
      font-size: 16px;
      margin-right: 10px;
    }
    .zk-talbe {
      margin-top: 10px;
      .menu-img {
        width: 20px;
        float:right;
        background:#000;
      }
    }
  }
</style>
